#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/stat.h>
#include<string.h>
#include<fcntl.h>


int main()
{
  int pipefd[2];
  int ret=pipe(pipefd);
  if(ret<0){
    perror("pipe error!");
    return -1;
  }


  pid_t ps_child=fork();
  if(ps_child==0){
    //子进程1:向管道中写入数据
    close(pipefd[0]);
    
    dup2(pipefd[1],1);    //标准输出写入管道
    execlp("ps","ps","-ef",NULL);
    exit(-1);
  }


  pid_t grep_child=fork();
  if(grep_child==0){
    //子进程2：从管道中读取数据
    close(pipefd[1]);
    dup2(pipefd[0],0);
    execlp("grep","grep","pipe",NULL);
    exit(-1);
  }


  //父进程关闭读写
  close(pipefd[0]);
  close(pipefd[1]);
  
  waitpid(ps_child,NULL,0);
  waitpid(grep_child,NULL,0);

  return 0;
}
